package com.yym.selevlet;

import com.yym.utils.DbUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/register")
public class RigsterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,RuntimeException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        System.out.println(username);
//        System.out.println(password);
        insertRegisterUser(username,password);
        System.out.println("插入成功");
        PrintWriter writer = response.getWriter();
        StringBuffer html = new StringBuffer();
        html.append("<html>")
                .append("<head></head>")
                .append("<body><h1>注册成功</h1>")
                .append("</body></html>");

         writer.write(html.toString());
            writer.flush();
            writer.close();

    }
    private void insertRegisterUser(String  username,String password)  {
        Connection connection = DbUtils.getConnection();
        String sql ="insert into user(username,password) values(？,？）";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1, username);
            preparedStatement.setObject(2, password);
            preparedStatement.executeUpdate();
            DbUtils.colse(null,preparedStatement,connection);
        }catch (SQLException sqlException){
            sqlException.printStackTrace();
        }

    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
